package com.ys.service.business.impl;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import com.ys.entity.amazonorder.TbBaseinfoSppm;
import com.ys.entity.base.TbFileInfo;
import com.ys.entity.business.TpAmazonShop;
import com.ys.service.sys.PdfService;
import com.ys.util.PdfUtil;
import io.swagger.client.model.LabelOwner;
import io.swagger.client.model.PrepOwner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.threeten.bp.OffsetDateTime;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.bo.sellingpartnerapi.Catalogitems20220401.api.CatalogApi;
import com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSearchResults;
import com.bo.sellingpartnerapi.Fbainventory.api.FbaInventoryApi;
import com.bo.sellingpartnerapi.Fbainventory.model.GetInventorySummariesResponse;
import com.bo.sellingpartnerapi.Feeds20210630.model.Feed;
import com.bo.sellingpartnerapi.Fulfillmentinboundv0.model.GetPrepInstructionsResponse;
import com.bo.sellingpartnerapi.Fulfillmentinboundv0.model.GetPrepInstructionsResult;
import com.bo.sellingpartnerapi.Fulfillmentinboundv0.model.PrepInstruction;
import com.bo.sellingpartnerapi.Fulfillmentinboundv0.model.SKUPrepInstructions;
import com.bo.sellingpartnerapi.Listingsitems20210801.api.ListingsApi;
import com.bo.sellingpartnerapi.Listingsitems20210801.invoker.ApiException;
import com.bo.sellingpartnerapi.Listingsitems20210801.model.Item;
import com.bo.sellingpartnerapi.Listingsitems20210801.model.ItemSummaryByMarketplace;
import com.bo.sellingpartnerapi.Reports20210630.api.ReportsApi;
import com.bo.sellingpartnerapi.Reports20210630.model.CreateReportResponse;
import com.bo.sellingpartnerapi.Reports20210630.model.CreateReportSpecification;
import com.bo.sellingpartnerapi.Reports20210630.model.Report;
import com.bo.sellingpartnerapi.Reports20210630.model.ReportDocument;
import com.bo.sellingpartnerapi.Reports20210630.model.ReportOptions;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.ys.config.MyConfig;
import com.ys.dto.AddDto;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.business.TpAmazonShopProductReport;
import com.ys.entity.business.TpProductActive;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpAmazonShopProductMapper;
import com.ys.service.business.TpAmazonShopProductService;
import com.ys.util.RandomUtil;
import com.ys.util.amazon.FbaInboundApi;
import com.ys.util.amazon.Helper;
import com.ys.util.amazon.SellerSecretsVO;
import com.ys.util.dhecp.DateUtils;
import com.ys.util.dhecp.MathExtUtils;
import com.ys.util.dhecp.StringUtils;
import com.ys.util.dhecp.TypeUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.R;

import cn.hutool.core.util.ZipUtil;

@Service("tpAmazonShopProductService")
public class TpAmazonShopProductServiceImpl implements TpAmazonShopProductService {

	@Autowired
	private TpAmazonShopProductMapper tpAmazonShopProductMapper;

	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
	private PdfService pdfService;

	public static Map<String, Integer> THREAD_MAP = new HashMap<String, Integer>() {{
		for (int i = 0; i < 200; i++) {
			put("threadAsin" + i, 0);
		}
	}};

	public static Map<String, Integer> THREAD_MAPASIN = new HashMap<String, Integer>() {{
		for (int i = 0; i < 200; i++) {
			put("threadAsin" + i, 0);
		}
	}};

	@Override
	public R add(Map<String, Object> params) {

        TpAmazonShopProduct entity = JSON.parseObject(JSON.toJSONString(params), TpAmazonShopProduct.class);
		entity.setPrepOwner("NONE");
		entity.setLabelOwner("NONE");
		tpAmazonShopProductMapper.insert(entity);
		return R.ok("操作成功");
	}

	/**
	 * 定时获取亚马逊店铺销售产品信息
	 */
	@Override
	public ApiResponse getAmazonSalesTrafficReport(JSONObject jsonObject,  String startTimeStr, String endTimeStr,String nowDateStr,List<TpAmazonShopProduct> amazonShopProductList,String encryptSecret) {
		ApiResponse apiResponse = new ApiResponse();
		String errorMsg = "";
		String result = "";
		List<String> marketplaceIdList =  new ArrayList<>();
		if(!StringUtils.isEmpty(jsonObject.get("marketplaceId").toString())) {
			String marketplaceIds = jsonObject.get("marketplaceId").toString();
			String[] marketplaceIdArray = marketplaceIds.split(",");
			marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
		}

		CreateReportSpecification body = new CreateReportSpecification();
		body.setReportType("GET_SALES_AND_TRAFFIC_REPORT");
		body.setMarketplaceIds(marketplaceIdList);
		body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
		body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
		ReportOptions reportOptions = new ReportOptions();
		reportOptions.put("dateGranularity","DAY");
		reportOptions.put("asinGranularity", "CHILD");
		body.setReportOptions(reportOptions);
		try {
			AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
					.accessKeyId(MyConfig.getAmazonAwsAccessKey())
					.secretKey(MyConfig.getAmazonAwsAccessSecret())
					.region(jsonObject.get("awsRegion").toString())
					.build();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
					.roleArn(MyConfig.getAmazonRoleArn())
					.roleSessionName(MyConfig.getAmazonRoleSessionName())
					.build();
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey())
					.clientSecret(encryptSecret)
					.refreshToken(jsonObject.get("refreshToken").toString())
					.endpoint(MyConfig.getAmazonLwaEndpoint())
					.build();

			ReportsApi reportsApi = new ReportsApi.Builder()
					.awsAuthenticationCredentials(awsAuthenticationCredentials)
					.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
					.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
					.endpoint(jsonObject.get("amazonServiceUrl").toString())
					.build();
			CreateReportResponse reportResponse =  null;
			TpAmazonShopProductReport tpAmazonShopProductReport = null;
			List<TpAmazonShopProductReport> tpAmazonShopProductReportList = new ArrayList<>();
			try {
				reportResponse = reportsApi.createReport(body);
				if (reportResponse != null){
					String reportId = reportResponse.getReportId();
					String reportDocumentId = "";
					Report report = null;
					Report.ProcessingStatusEnum processingStatus = null;
					while (true){
						report = reportsApi.getReport(reportId);
						processingStatus = report.getProcessingStatus();
						if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
								|| Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
								|| Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
							if (report != null) {
								reportDocumentId = report.getReportDocumentId();
							}
							break;
						}else {
							Thread.sleep(10000L);
							continue;
						}
					}
					if (report != null){
						if (!StringUtils.isEmpty(reportDocumentId)) {
							ReportDocument reportDocument = reportsApi.getReportDocument(reportDocumentId);
							if (reportDocument != null) {
								String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
								OkHttpClient httpclient = new OkHttpClient();
								httpclient.setConnectTimeout(30, TimeUnit.SECONDS);
								httpclient.setReadTimeout(30, TimeUnit.SECONDS);
								httpclient.setWriteTimeout(30, TimeUnit.SECONDS);
								Request request = new Request.Builder()
										.url(reportDocument.getUrl())
										.get()
										.build();

								Response httpResponse = httpclient.newCall(request).execute();
								if (!httpResponse.isSuccessful()) {
									result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
									apiResponse.setCode(500);
									apiResponse.setMsg(result);
									return apiResponse;
								}
								try (ResponseBody responseBody = httpResponse.body()) {
									MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
									Charset charset = mediaType.charset();
									if (charset == null) {
										result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString();
										apiResponse.setCode(500);
										apiResponse.setMsg(result);
										return apiResponse;
									}
									Closeable closeThis = null;
									try {
										InputStream inputStream = responseBody.byteStream();
										closeThis = inputStream;
										if ("GZIP".equals(compressionAlgorithm)) {
											closeThis = inputStream;
											inputStream = new GZIPInputStream(inputStream);
											byte[] zipBytes = ZipUtil.unGzip(inputStream);
											String filePath = MyConfig.getProfile() + "/amazonreport/salestraffic/"+nowDateStr.replace("-", "");
											String gzOutPath =  filePath + "/salestraffic_report_" + jsonObject.get("id").toString();
											File gzOutFileObj= new File(gzOutPath);
											if(!gzOutFileObj.exists()){
												gzOutFileObj.mkdirs();
											}
											String gzFileNamePrefix = "salestraffic_report_" + jsonObject.get("id").toString();
											String fileName = gzFileNamePrefix +".txt";
											//将文件解压到gzOutPath目录中
											File gzOutFile = new File(gzOutPath + "/"+fileName);
											FileOutputStream fileOutputStream = new FileOutputStream(gzOutFile);
											fileOutputStream.write(zipBytes);
											fileOutputStream.close();
											File[] txtFileList = gzOutFileObj.listFiles();
											InputStream txtInputStream = null;
											StringBuffer txtStringBuffer = null;
											BufferedReader txtBufferedReader = null;
											if (txtFileList != null && txtFileList.length  > 0){
												for (File txtFileItem : txtFileList) {
													txtInputStream = new FileInputStream(txtFileItem);
													String txtLine; // 用来保存每行读取的内容
													txtStringBuffer = new StringBuffer();
													txtBufferedReader = new BufferedReader(new InputStreamReader(txtInputStream));
													txtLine = txtBufferedReader.readLine(); // 读取第一行
													while (txtLine != null) { // 如果 line 为空说明读完了
														txtStringBuffer.append(txtLine); // 将读到的内容添加到 buffer 中
														txtStringBuffer.append("\n"); // 添加换行符
														txtLine = txtBufferedReader.readLine(); // 读取下一行
													}
													if(txtBufferedReader != null) txtBufferedReader.close();
													if(txtInputStream != null) txtInputStream.close();
													String txtContent = txtStringBuffer.toString();
													if (!StringUtils.isEmpty(txtContent)){
														JSONObject jsonObjecttxtContent = JSON.parseObject(txtContent);
														if (jsonObjecttxtContent != null){
															JSONArray jsonArray = jsonObjecttxtContent.getJSONArray("salesAndTrafficByAsin");
															if (jsonArray != null && jsonArray.size() > 0){
																for(int i=0;i<jsonArray.size();i++) {
																	JSONObject itemJsonObj = jsonArray.getJSONObject(i);
																	String asin = itemJsonObj.getString("parentAsin");
																	JSONObject trafficByAsinObj = itemJsonObj.getJSONObject("trafficByAsin");
																	Integer sessions = trafficByAsinObj.getInteger("pageViews");
																	Double buyBoxPercentage = trafficByAsinObj.getDouble("buyBoxPercentage");
																	Double sessionPercentage = trafficByAsinObj.getDouble("unitSessionPercentage");
																	for (TpAmazonShopProduct tpAmazonShopProduct : amazonShopProductList) {
																		if (tpAmazonShopProduct.getAsin().equals(asin) && tpAmazonShopProduct.getMarketplaceId().equals(jsonObject.get("marketplaceId").toString())) {
																			tpAmazonShopProduct.setSessionsNum(sessions);
																			tpAmazonShopProduct.setCommoditySession(new BigDecimal(sessionPercentage).setScale(2, BigDecimal.ROUND_HALF_UP));
																			tpAmazonShopProduct.setRecommendPrice(new BigDecimal(buyBoxPercentage).setScale(2, BigDecimal.ROUND_HALF_UP));
																			tpAmazonShopProduct.setUpdateTime(new Date());

																			tpAmazonShopProductReport = new TpAmazonShopProductReport();
																			tpAmazonShopProductReport.setShopProductGuid(tpAmazonShopProduct.getGuid());
																			tpAmazonShopProductReport.setShopProductId(String.valueOf(tpAmazonShopProduct.getId()));
																			tpAmazonShopProductReport.setSessionsNum(sessions);
																			tpAmazonShopProductReport.setCommoditySession(new BigDecimal(sessionPercentage).setScale(2, BigDecimal.ROUND_HALF_UP));
																			tpAmazonShopProductReport.setRecommendPrice(new BigDecimal(buyBoxPercentage).setScale(2, BigDecimal.ROUND_HALF_UP));
																			tpAmazonShopProductReport.setDataDate(nowDateStr);
																			tpAmazonShopProductReportList.add(tpAmazonShopProductReport);
																		}
																	}
																}
															}
														}
													}
												}
												//批量修改商品信息
												diySqlMapper.updateTpAmazonShopProductBatchNew(amazonShopProductList);
												//批量修改商品每天数据
												diySqlMapper.updateTpAmazonShopProductReportBatch(tpAmazonShopProductReportList);
											}
										}else if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
											InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
											closeThis = inputStreamReader;
										}
									}catch (Exception ex){
										result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地方为获取responseBody.byteStream()文件流出错！";
										apiResponse.setCode(500);
										apiResponse.setMsg(result);
										return apiResponse;
									}
									finally {
										if(responseBody != null){
											responseBody.close();
										}
										if (closeThis != null) {
											closeThis.close();
										}
									}
								}
							} else {
								result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReportDocument接口返回对象为空！";
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}
						}else {
							if(processingStatus != null && Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())){
								result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表["+nowDateStr+"]这天没有数据，其中report对象值："+ JSON.toJSONString(report);
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}else {
								result = "获取亚马逊单个店铺[" + jsonObject.get("shopUser").toString() + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值：" + JSON.toJSONString(report) + "，具体错误为调用getReport接口返回reportDocumentId值为空！";
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}
						}
					}else {
						result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中reportId值："+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！";
						apiResponse.setCode(500);
						apiResponse.setMsg(result);
						return apiResponse;
					}
				}else{
					result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为调用createReport接口返回对象为空！";
					apiResponse.setCode(500);
					apiResponse.setMsg(result);
					return apiResponse;
				}
			}catch (com.bo.sellingpartnerapi.Reports20210630.invoker.ApiException ex){
				JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
				if (errorJson != null){
					JSONArray errorList = errorJson.getJSONArray("errors");
					if (errorList != null && errorList.size() > 0) {
						errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
						for (int i = 0; i < errorList.size(); i++) {
							JSONObject failedItem = errorList.getJSONObject(i);
							String message = failedItem.getString("message");
							errorMsg += message + "\n\r";
						}
					}
				}
				result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+errorMsg;
				apiResponse.setCode(500);
				apiResponse.setMsg(result);
				return apiResponse;
			}
		}catch(Exception ex){
			result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+ex.getMessage();
			apiResponse.setCode(500);
			apiResponse.setMsg(result);
			return apiResponse;
		}
		return apiResponse;
	}

	/**
	 * 定时获取亚马逊店铺销售产品信息
	 */
	@Override
	public ApiResponse getAllAmazonShopProductPriceReport(JSONObject jsonObject, String startTimeStr, String endTimeStr,String nowDateStr,List<TpAmazonShopProduct> amazonShopProductList,String encryptSecret) {
		ApiResponse apiResponse = new ApiResponse();
		String errorMsg = "";
		String result = "";
		List<String> marketplaceIdList =  new ArrayList<>();
		if(!StringUtils.isEmpty(jsonObject.get("marketplaceId").toString())) {
			String marketplaceIds = jsonObject.get("marketplaceId").toString();
			String[] marketplaceIdArray = marketplaceIds.split(",");
			marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
		}
		CreateReportSpecification body = new CreateReportSpecification();
		body.setReportType("GET_MERCHANT_LISTINGS_ALL_DATA");
		body.setMarketplaceIds(marketplaceIdList);
		body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
		body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
		ReportOptions reportOptions = new ReportOptions();
		reportOptions.put("custom", "true");
		body.setReportOptions(reportOptions);
		TpAmazonShopProductReport tpAmazonShopProductReport = null;
		List<TpAmazonShopProductReport> tpAmazonShopProductReportList = new ArrayList<>();
		try {
			AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
					.accessKeyId(MyConfig.getAmazonAwsAccessKey())
					.secretKey(MyConfig.getAmazonAwsAccessSecret())
					.region(jsonObject.get("awsRegion").toString())
					.build();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
					.roleArn(MyConfig.getAmazonRoleArn())
					.roleSessionName(MyConfig.getAmazonRoleSessionName())
					.build();
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey())
					.clientSecret(encryptSecret)
					.refreshToken(jsonObject.get("refreshToken").toString())
					.endpoint(MyConfig.getAmazonLwaEndpoint())
					.build();

			ReportsApi reportsApi = new ReportsApi.Builder()
					.awsAuthenticationCredentials(awsAuthenticationCredentials)
					.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
					.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
					.endpoint(jsonObject.get("amazonServiceUrl").toString())
					.build();
			CreateReportResponse reportResponse =  null;
			try {
				reportResponse = reportsApi.createReport(body);
				if (reportResponse != null){
					String reportId = reportResponse.getReportId();
					String reportDocumentId = "";
					Report report = null;
					Report.ProcessingStatusEnum processingStatus = null;
					while (true){
						report = reportsApi.getReport(reportId);
						processingStatus = report.getProcessingStatus();
						if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
								|| Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
								|| Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
							if (report != null) {
								reportDocumentId = report.getReportDocumentId();
							}
							break;
						}else {
							Thread.sleep(10000L);
							continue;
						}
					}
					if (report != null){
						if (!StringUtils.isEmpty(reportDocumentId)) {
							ReportDocument reportDocument = reportsApi.getReportDocument(reportDocumentId);
							if (reportDocument != null) {
								String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
								OkHttpClient httpclient = new OkHttpClient();
								httpclient.setConnectTimeout(30, TimeUnit.SECONDS);
								httpclient.setReadTimeout(30, TimeUnit.SECONDS);
								httpclient.setWriteTimeout(30, TimeUnit.SECONDS);
								Request request = new Request.Builder()
										.url(reportDocument.getUrl())
										.get()
										.build();

								Response httpResponse = httpclient.newCall(request).execute();
								if (!httpResponse.isSuccessful()) {
									result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
									apiResponse.setCode(500);
									apiResponse.setMsg(result);
									return apiResponse;
								}
								try (ResponseBody responseBody = httpResponse.body()) {
									MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
									Charset charset = mediaType.charset();
									if (charset == null) {
										result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString();
										apiResponse.setCode(500);
										apiResponse.setMsg(result);
										return apiResponse;
									}
									Closeable closeThis = null;
									try {
										InputStream inputStream = responseBody.byteStream();
										closeThis = inputStream;
										if ("GZIP".equals(compressionAlgorithm)) {
											inputStream = new GZIPInputStream(inputStream);
											closeThis = inputStream;
										}
										if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
											InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
											closeThis = inputStreamReader;
											BufferedReader reader = new BufferedReader(inputStreamReader);
											closeThis = reader;
											StringBuilder stringBuilder = new StringBuilder();
											String line ;
											do {
												line = reader.readLine();
												if (line != null) {
													stringBuilder.append(line);
													stringBuilder.append("\n");
												}
											} while (line != null);
											String filePath = MyConfig.getProfile() + "/amazonreport/listings/"+nowDateStr.replace("-", "");
											String fileName = "listings_report_" + jsonObject.get("id").toString()+ ".cvs";
											File file = new File(filePath);
											if(!file.exists()){
												file.mkdirs();
											}
											File reportFile = new File(filePath + "/"+ fileName);
											if (!reportFile.exists()){
												reportFile.createNewFile();
											}
											OutputStream outputStream = new FileOutputStream(reportFile);
											outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
											outputStream.close();
											BufferedReader csvBufferedReader = null;
											String reportLine = "";
											String separator = "\t";
											try {
												InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/" + fileName), StandardCharsets.UTF_8);
												csvBufferedReader = new BufferedReader(csvInputStreamReader);
												String title = csvBufferedReader.readLine();
												String[] titleSplit = title.split(separator);
												while ((reportLine = csvBufferedReader.readLine()) != null) {
													if (!StringUtils.isEmpty(reportLine)) {
														//内容数组
														String[] reportArray = reportLine.split(separator);
														//判断内容和标题的size
														if ((reportArray.length) < titleSplit.length) {
															int len = titleSplit.length - reportArray.length;
															reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
														}
														String sellerSku = reportArray[3];
														String priceStr = reportArray[4];
														String asin = reportArray[16];
														for (TpAmazonShopProduct tpAmazonShopProduct : amazonShopProductList) {
															if (tpAmazonShopProduct.getSellerSku().equals(sellerSku) && tpAmazonShopProduct.getMarketplaceId().equals(jsonObject.get("marketplaceId").toString())) {
																tpAmazonShopProduct.setSellerSku(sellerSku);
																tpAmazonShopProduct.setAsin(asin);
																tpAmazonShopProduct.setListingPrice(BigDecimal.valueOf(TypeUtils.getSafeDouble(priceStr, 0d)));
																tpAmazonShopProduct.setUpdateTime(new Date());

																tpAmazonShopProductReport = new TpAmazonShopProductReport();
																tpAmazonShopProductReport.setListingPrice(BigDecimal.valueOf(TypeUtils.getSafeDouble(priceStr, 0d)));
																tpAmazonShopProductReport.setDataDate(nowDateStr);
																tpAmazonShopProductReport.setShopProductGuid(tpAmazonShopProduct.getGuid());
																tpAmazonShopProductReport.setShopProductId(String.valueOf(tpAmazonShopProduct.getId()));
																tpAmazonShopProductReportList.add(tpAmazonShopProductReport);
															}
														}
													}
												}
												//批量修改商品信息
												diySqlMapper.updateTpAmazonShopProductBatchNew(amazonShopProductList);
												//批量修改商品每天数据
												diySqlMapper.updateTpAmazonShopProductReportBatch(tpAmazonShopProductReportList);
											}catch (Exception ex){
												result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时出错！";
												apiResponse.setCode(500);
												apiResponse.setMsg(result);
												return apiResponse;
											}

										}
									}catch (Exception ex){
										result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地方为获取responseBody.byteStream()文件流出错！";
										apiResponse.setCode(500);
										apiResponse.setMsg(result);
										return apiResponse;
									}
									finally {
										if(responseBody != null){
											responseBody.close();
										}
										if (closeThis != null) {
											closeThis.close();
										}
									}
								}
							} else {
								result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReportDocument接口返回对象为空！";
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}
						}else {
							if(processingStatus != null && Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())){
								result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表["+nowDateStr+"]这天没有数据，其中report对象值："+ JSON.toJSONString(report);
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}else {
								result = "获取亚马逊单个店铺[" + jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值：" + JSON.toJSONString(report) + "，具体错误为调用getReport接口返回reportDocumentId值为空！";
								apiResponse.setCode(500);
								apiResponse.setMsg(result);
								return apiResponse;
							}
						}
					}else {
						result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中reportId值："+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！";
						apiResponse.setCode(500);
						apiResponse.setMsg(result);
						return apiResponse;
					}
				}else{
					result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为调用createReport接口返回对象为空！";
					apiResponse.setCode(500);
					apiResponse.setMsg(result);
					return apiResponse;
				}
			}catch (com.bo.sellingpartnerapi.Reports20210630.invoker.ApiException ex){
				JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
				if (errorJson != null){
					JSONArray errorList = errorJson.getJSONArray("errors");
					if (errorList != null && errorList.size() > 0) {
						errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
						for (int i = 0; i < errorList.size(); i++) {
							JSONObject failedItem = errorList.getJSONObject(i);
							String message = failedItem.getString("message");
							errorMsg += message + "\n\r";
						}
					}
				}
				result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+errorMsg;
				apiResponse.setCode(500);
				apiResponse.setMsg(result);
				return apiResponse;
			}
		}catch(Exception ex){
			result = "获取亚马逊单个店铺["+ jsonObject.get("shopUser").toString()  + "-" + jsonObject.get("shopName").toString() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+ex.getMessage();
			apiResponse.setCode(500);
			apiResponse.setMsg(result);
			return apiResponse;
		}
		return apiResponse;
	}


	/**
	 * Lisiting 保存网店商品信息
	 * @param params
	 * @param subData
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, String subData) throws Exception {

		String code = params.get("code").toString();
		// 验证是否有详情数据
		JSONArray detailJA = JSON.parseArray(subData);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("SKU列表不能为空");
		}
		TpAmazonShopProduct tpAmazonShopProduct = new TpAmazonShopProduct();
		List<Map<String, String>> skuList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			if (detailJO.get("sellerSku") == null || detailJO.get("sellerSku").equals("")){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("SKU不能为空");
			}else {
				//不允许双引和单引号
				String regex = "^[^'\"]*$";
				if (!detailJO.get("sellerSku").toString().matches(regex)){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("SKU不能存在单引号或者双引号!");
				}
			}
			if (detailJO.get("sellerId") == null || detailJO.get("sellerId").equals("")){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("平台编号不能为空");
			}
			if (detailJO.get("isSign").equals("是")){
				if (detailJO.get("signCode") == null || detailJO.get("signCode").equals("")){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("透明标记编码不可为空");
				}
			}
			TpProductActive tpProductActive = new TpProductActive().setCode(code).queryFirst();
			if (tpProductActive == null){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("该Listing信息不存在,核实再操作!");
			}
			if (tpProductActive.getIsSuperior().equals("是")) {
				Map<String, String> sku = new LinkedHashMap<String, String>();
				sku.put("id", detailJO.get("sellerId").toString());
				sku.put("sku", detailJO.get("sellerSku").toString());
				sku.put("markId", detailJO.get("marketplaceId").toString());
				sku.put("marketplaceName", detailJO.get("marketplaceName").toString());
				skuList.add(sku);

				for (Map<String, String> sid : skuList
				) {
//					if (sid.get("id").equals(detailJO.get("sellerId").toString()) && sid.get("markId").equals(detailJO.get("marketplaceId").toString())) {
//						if (!sid.get("sku").equals(detailJO.get("sellerSku").toString())) {
//							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//							return R.error("同一个店铺不可添加不同的sku");
//						}
//						continue;
//					}
					//平台编号相同，可以添加。不相同时只能区域不同才可以添加
					if (sid.get("id").equals(detailJO.get("sellerId").toString())) {
						continue;
					}else {
						if (sid.get("marketplaceName").equals(detailJO.get("marketplaceName").toString())){
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("不同平台编码，相同区域，不能添加SKU！");
						}
					}

				}
			}
			if (detailJO.get("guid") != null) {
				Map oldData = new TpAmazonShopProduct().setGuid(detailJO.get("guid").toString())
						.addField("t2.SellerId")
						.addLeftJoin("TP_AmazonShop t2 on A.shopId = t2.id ")
						.queryFirstMap();
				//有asin的网上商品信息不允许修改
				if (oldData != null) {
					if (oldData.get("asin") != null) {
						if (!oldData.get("sellerSku").equals(detailJO.get("sellerSku").toString())) {
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("SKU已经关联Asin不允许修改SKU信息,如需修改请删除后重新关联!");
						}
						if (!oldData.get("SellerId").equals(detailJO.get("sellerId").toString())) {
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("SKU已经关联Asin不允许修改平台编码信息,如需修改请删除后重新关联!");
						}
					}
				}
			}

			List<Map<String, Object>> productSku = new TpAmazonShopProduct()
					.setSellerSku(detailJO.get("sellerSku").toString())
					.addLeftJoin("TP_AmazonShop t2 on A.ShopId = t2.id")
					.addField("t2.shopName as shopName")
					.queryMap();
			//判断是否存在数据
			if (productSku.size() > 0) {
				for (Map<String, Object> sku : productSku
				) {
					if (detailJO.get("sellerSku").toString().equals(sku.get("sellerSku").toString())) {
						//判断是否同公司
						if (!detailJO.get("shopName").toString().split("-")[0].equals(sku.get("shopName").toString().split("-")[0])){
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("当前SKU已存在不可重复添加");
						}

						String guid = null;
						if (detailJO.get("guid") != null){
							guid = detailJO.get("guid").toString();
						}
						//判断是否同大区
						if (sku.get("marketplaceId").toString().equals(detailJO.get("marketplaceId").toString()) &&  !Objects.equals(guid, sku.get("guid"))
//						if (sku.get("marketplaceId").toString().equals(detailJO.get("marketplaceId").toString()) && !sku.get("code").toString().equals(detailJO.get("code").toString())
								) {
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error("当前SKU已存在不可重复添加");
						}
//						if (detailJO.get("guid") != null){
//							if (!Objects.equals(detailJO.get("guid").toString(), sku.get("guid").toString())) {
//								TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//								return R.error("当前SKU已存在不可重复添加");
//							}
//						}
					} else {
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error("当前SKU已存在不可重复添加");
					}

					//判断是否存在不同商品的SKU 20241210 取消不同商品不允许新增
//					if (!detailJO.get("code").toString().equals(sku.get("code").toString())){
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return R.error("当前SKU已存在不可重复添加");
//					}

				}
			}

			if (detailJO.get("guid") != null) {
				tpAmazonShopProduct.setId(Long.valueOf(detailJO.get("id").toString()));
				tpAmazonShopProduct.setCode(detailJO.get("code").toString());
				tpAmazonShopProduct.setSellerSku(detailJO.get("sellerSku").toString().trim());
				tpAmazonShopProduct.setShopId(Long.valueOf(detailJO.get("shopId").toString()));
				tpAmazonShopProduct.setMarketplaceId(detailJO.get("marketplaceId").toString());
				tpAmazonShopProduct.setIsSign(detailJO.get("isSign").toString());
				if (detailJO.get("signCode") != null){
					if(tpAmazonShopProduct.getIsSign().equals("否")){
						tpAmazonShopProduct.setSignCode("");
					}else {
						tpAmazonShopProduct.setSignCode(detailJO.get("signCode").toString());
					}
				}
				tpAmazonShopProduct.setCountIsShow(Integer.valueOf(detailJO.get("countIsShow").toString()));
				tpAmazonShopProductMapper.update(tpAmazonShopProduct);

			}else {
				tpAmazonShopProduct.setCode(detailJO.get("code").toString());
				tpAmazonShopProduct.setGuid(RandomUtil.getGUID());
				tpAmazonShopProduct.setSellerSku(detailJO.get("sellerSku").toString().trim());
				tpAmazonShopProduct.setShopId(Long.valueOf(detailJO.get("shopId").toString()));
				tpAmazonShopProduct.setShopGuid(detailJO.get("shopGuid").toString());
				tpAmazonShopProduct.setMarketplaceId(detailJO.get("marketplaceId").toString());
				tpAmazonShopProduct.setIsSign(detailJO.get("isSign").toString());
				if (detailJO.get("signCode") != null){
					if(tpAmazonShopProduct.getIsSign().equals("否")){
						tpAmazonShopProduct.setSignCode("");
					}else {
						tpAmazonShopProduct.setSignCode(detailJO.get("signCode").toString());
					}
				}
				tpAmazonShopProduct.setCountIsShow(Integer.valueOf(detailJO.get("countIsShow").toString()));
				tpAmazonShopProduct.setCreateTime(new Date());
				tpAmazonShopProduct.setCreateUser(ShiroUtils.getUserId());
				tpAmazonShopProduct.setPrepOwner("NONE");
				tpAmazonShopProduct.setLabelOwner("NONE");
				tpAmazonShopProductMapper.insert(tpAmazonShopProduct);
			}
		}
		return R.ok(AddDto.gotoEdit("/web/business/tpProductActive/bindShop?code=" + code));
	}


	/**
	 * 删除
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R delete(Long id) {
		try {
			TpAmazonShopProduct tpAmazonShopProduct = new TpAmazonShopProduct().setId(id).queryFirst();
			if (tpAmazonShopProduct == null){
				R.error("SKU信息不存在!");
			}
			tpAmazonShopProductMapper.deleteTrue(tpAmazonShopProduct.getId());

		} catch (Exception e) {
			return R.error("删除失败!");
		}
		return R.ok("删除成功!");
	}


	/**
	 * 打印预览
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public R doPrint(Long id) throws Exception {
		//查询网店商品
		TpAmazonShopProduct tpAmazonShopProduct = new TpAmazonShopProduct().setId(id).queryFirst();
		//查询店铺信息
		TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tpAmazonShopProduct.getShopId()).queryFirst();
		//查询Listing数据
		TpProductActive tpProductActive = new TpProductActive().setCode(tpAmazonShopProduct.getCode()).queryFirst();
		//查询附件
		List<TbFileInfo> tbFileInfos = new TbFileInfo().setSourceId(tpAmazonShopProduct.getId()).setSourceType(43).setSourceCode("esAnnexFile").setStatus(1).queryList();

		TbBaseinfoSppm tbBaseinfoSppm = new TbBaseinfoSppm().setId(tpProductActive.getNameId()).queryFirst();

		LocalDate currentDate = LocalDate.now();
		LocalDate previousDate = currentDate.minusDays(7);
		// 创建SimpleDateFormat对象，设置英文日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM dd, yyyy", Locale.ENGLISH);
		Date date1 = Date.from(previousDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
		// 将日期转换为英文字符串
		String dateInEnglish = sdf.format(date1);

		List<PdfService.EuropeanStandardPrintDto> europeanStandardPrintDtoList = new ArrayList<>();

		PdfService.EuropeanStandardPrintDto dto = new PdfService.EuropeanStandardPrintDto(tbBaseinfoSppm.getNameEn(),
				tpProductActive.getCode()+'/'+tpAmazonShopProduct.getFnSku(), tpAmazonShop.getEuAgent(), tpAmazonShop.getEuAgentAddress(), tpAmazonShop.getManufacturer()
				, tpAmazonShop.getManufacturerAddress(),tpProductActive.getAgeRange(),dateInEnglish,1,tbFileInfos);
		europeanStandardPrintDtoList.add(dto);

		String url = pdfService.europeanStandardPrint(tpAmazonShopProduct.getCode(),europeanStandardPrintDtoList);
		return R.ok(url);
	}


	/**
	 * 定时获取亚马逊店铺销售产品信息
	 */
	@Override
	public ApiResponse getAsinAndProductInfo(JSONObject jsonObject, String nowDateStr, String updateUserId,String encryptSecret) {
		ApiResponse apiResponse = new ApiResponse();
		try {
			AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
					.accessKeyId(MyConfig.getAmazonAwsAccessKey())
					.secretKey(MyConfig.getAmazonAwsAccessSecret())
					.region(jsonObject.get("awsRegion").toString())
					.build();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
					.roleArn(MyConfig.getAmazonRoleArn())
					.roleSessionName(MyConfig.getAmazonRoleSessionName())
					.build();
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey())
					.clientSecret(encryptSecret)
					.refreshToken(jsonObject.get("refreshToken").toString())
					.endpoint(MyConfig.getAmazonLwaEndpoint())
					.build();

			String asin = jsonObject.get("asin") == null?null :jsonObject.get("asin").toString();
			String fnSku = "";
			//如果asin为空，调用get Listings Item接口通过sku获取
			if (StringUtils.isEmpty(jsonObject.get("asin")) || jsonObject.get("type").toString().equals("0")) {
				ListingsApi listingsApi = new ListingsApi.Builder()
						.awsAuthenticationCredentials(awsAuthenticationCredentials)
						.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
						.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
						.endpoint(jsonObject.get("amazonServiceUrl").toString())
						.build();
				List<String> listMarketplaceIds = new ArrayList<String>();
				listMarketplaceIds.add(jsonObject.get("marketplaceId").toString());
				List<String> listIncludedData = new ArrayList<>();
				listIncludedData.add("issues");
				listIncludedData.add("attributes");
				listIncludedData.add("summaries");
				listIncludedData.add("offers");
				listIncludedData.add("fulfillmentAvailability");
				String listIssueLocale = "en_US";
				Item listingsItem = null;
				try {
					listingsItem = listingsApi.getListingsItem(
							jsonObject.get("sellerId").toString(), jsonObject.get("sellerSku").toString(),
							listMarketplaceIds, listIssueLocale, listIncludedData);
				} catch (ApiException e) {
					e.printStackTrace();
					apiResponse.setCode(500);
					apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+e.getResponseBody());
					return apiResponse;
				}
				if (listingsItem != null && listingsItem.getSummaries() != null && listingsItem.getSummaries().size() > 0) {
					for (ItemSummaryByMarketplace itemSummaryByMarketplace : listingsItem.getSummaries()) {
						asin = itemSummaryByMarketplace.getAsin();
						fnSku = itemSummaryByMarketplace.getFnSku();
						jsonObject.put("asin", asin);
						jsonObject.put("fnSku", fnSku);
					}
				}
			}
			if (!StringUtils.isEmpty(asin)) {
				//根据get Catalog Item获取产品相关信息
				CatalogApi catalogApi = new CatalogApi.Builder()
						.awsAuthenticationCredentials(awsAuthenticationCredentials)
						.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
						.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
						.endpoint(jsonObject.get("amazonServiceUrl").toString())
						.build();
				List<String> catalogMarketplaceIds = new ArrayList<String>();
				catalogMarketplaceIds.add(jsonObject.get("marketplaceId").toString());
				List<String> catalogIncludedData = new ArrayList<>();
				catalogIncludedData.add("attributes");
				catalogIncludedData.add("dimensions");
				catalogIncludedData.add("identifiers");
				catalogIncludedData.add("images");
				catalogIncludedData.add("productTypes");
				catalogIncludedData.add("salesRanks");
				catalogIncludedData.add("summaries");
				catalogIncludedData.add("relationships");
				com.bo.sellingpartnerapi.Catalogitems20220401.model.Item catalogItem = null;
				try {
					catalogItem = catalogApi.getCatalogItem(asin, catalogMarketplaceIds, catalogIncludedData, "en_US");
				} catch (com.bo.sellingpartnerapi.Catalogitems20220401.invoker.ApiException ex) {
					ex.printStackTrace();
					apiResponse.setCode(500);
					apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getMessage());
					return apiResponse;
				}
				if (catalogItem != null) {
					//获取产品品牌
					if (catalogItem.getSummaries() != null && catalogItem.getSummaries().size() > 0) {
						com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSummaryByMarketplace itemSummaryByMarketplace = catalogItem.getSummaries().get(0);
						if (itemSummaryByMarketplace != null) {
							jsonObject.put("brand", itemSummaryByMarketplace.getBrand());
						}
					}
					//获取产品图片
					if (catalogItem.getImages() != null && catalogItem.getImages().size() > 0) {
						com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImagesByMarketplace itemImagesByMarketplace = catalogItem.getImages().get(0);
						if (itemImagesByMarketplace != null && itemImagesByMarketplace.getImages() != null && itemImagesByMarketplace.getImages().size() > 0) {
							com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImage itemImage = itemImagesByMarketplace.getImages().get(0);
							if (itemImage != null) {
								jsonObject.put("link", itemImage.getLink());
								jsonObject.put("mainImage", itemImage.getLink());
							}
						}
					}
					//获取产品类别
					if (catalogItem.getProductTypes() != null && catalogItem.getProductTypes().size() > 0) {
						com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemProductTypeByMarketplace itemProductTypeByMarketplace = catalogItem.getProductTypes().get(0);
						if (itemProductTypeByMarketplace != null) {
							jsonObject.put("productType", itemProductTypeByMarketplace.getProductType());
						}
					}
					//获取产品排名
					if (catalogItem.getSalesRanks() != null && catalogItem.getSalesRanks().size() > 0) {
						com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSalesRanksByMarketplace itemSalesRanksByMarketplace = catalogItem.getSalesRanks().get(0);
						if (itemSalesRanksByMarketplace != null && itemSalesRanksByMarketplace.getDisplayGroupRanks() != null && itemSalesRanksByMarketplace.getDisplayGroupRanks().size() > 0) {
							com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDisplayGroupSalesRank itemDisplayGroupSalesRank = itemSalesRanksByMarketplace.getDisplayGroupRanks().get(0);
							if (itemDisplayGroupSalesRank != null) {
								jsonObject.put("salesRank", itemDisplayGroupSalesRank.getRank());
							}
						}
					}
					//获取产品尺寸与包装尺寸
					if (catalogItem.getDimensions() != null && catalogItem.getDimensions().size() > 0) {
						com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDimensionsByMarketplace itemDimensionsByMarketplace = catalogItem.getDimensions().get(0);
						if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getItem() != null) {
							jsonObject.put("sizeLength", (itemDimensionsByMarketplace.getItem().getLength() != null && itemDimensionsByMarketplace.getItem().getLength().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getLength().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);//将英寸转成厘米
							jsonObject.put("sizeHeight", (itemDimensionsByMarketplace.getItem().getHeight() != null && itemDimensionsByMarketplace.getItem().getHeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getHeight().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);//将英寸转成厘米
							jsonObject.put("sizeWidth", (itemDimensionsByMarketplace.getItem().getWidth() != null && itemDimensionsByMarketplace.getItem().getWidth().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getWidth().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);//将英寸转成厘米
						}
						if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getPackage() != null) {
							jsonObject.put("packageLength", (itemDimensionsByMarketplace.getPackage().getLength() != null && itemDimensionsByMarketplace.getPackage().getLength().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getLength().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);
							jsonObject.put("packageHeight", (itemDimensionsByMarketplace.getPackage().getHeight() != null && itemDimensionsByMarketplace.getPackage().getHeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getHeight().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);
							jsonObject.put("packageWidth", (itemDimensionsByMarketplace.getPackage().getWidth() != null && itemDimensionsByMarketplace.getPackage().getWidth().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getWidth().getValue().multiply(new BigDecimal("2.54")).doubleValue(), 2) : 0d);
							jsonObject.put("packageWeight", (itemDimensionsByMarketplace.getPackage().getWeight() != null && itemDimensionsByMarketplace.getPackage().getWeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getWeight().getValue().multiply(new BigDecimal("0.45359237")).doubleValue(), 2) : 0d);//将磅转成千克
						}
					}
				}
				SellerSecretsVO secretsVO = new SellerSecretsVO();
				secretsVO.setAWSAuthenticationCredentials_AK(MyConfig.getAmazonAwsAccessKey());
				secretsVO.setAWSAuthenticationCredentials_SK(MyConfig.getAmazonAwsAccessSecret());
				secretsVO.setAWSAuthenticationCredentialsProvider_roleArn(MyConfig.getAmazonRoleArn());
				secretsVO.setlWAAuthorizationCredentials_clientid(MyConfig.getAmazonLwaClientKey());
				secretsVO.setLWAAuthorizationCredentials_clientSecret(encryptSecret);
				secretsVO.setSeller_id(jsonObject.get("sellerId").toString());
				secretsVO.setLWAAuthorizationCredentials_refreshToken(jsonObject.get("refreshToken").toString());
				String amazonRegionCode = jsonObject.get("amazonRegionCode") == null ? "" : jsonObject.get("amazonRegionCode").toString();
				secretsVO.setMarketPlace(amazonRegionCode);

				String countryCode = jsonObject.get("countryCode") == null ? "" : jsonObject.get("countryCode").toString();


				List<String> sellerSKUList = new ArrayList<>();
				sellerSKUList.add(jsonObject.get("sellerSku").toString());
				FbaInboundApi fbaInboundApi = Helper.buildApi(secretsVO, FbaInboundApi.class);
				GetPrepInstructionsResponse getPrepInstructionsResponseList = fbaInboundApi.getPrepInstructions(countryCode, sellerSKUList, null);
				StringBuilder prepInstructionList = new StringBuilder();
				if (getPrepInstructionsResponseList != null){
					GetPrepInstructionsResult payload = getPrepInstructionsResponseList.getPayload();
					if (payload.getSkUPrepInstructionsList() != null){
						for(SKUPrepInstructions skuPrepInstructions :payload.getSkUPrepInstructionsList()){
							if (skuPrepInstructions.getPrepInstructionList() != null){
								for (PrepInstruction prepInstruction : skuPrepInstructions.getPrepInstructionList()){
									if(prepInstructionList.length()!=0){
										prepInstructionList.append(","+prepInstruction.getValue());
									}else{
										prepInstructionList.append(prepInstruction.getValue());
									}
								}
							}
						}
					}
				}

				//保存产品更新信息
				jsonObject.put("updateUser", updateUserId);
				jsonObject.put("prepInstructionList", prepInstructionList.toString());
				TpAmazonShopProduct tpAmazonShopProduct = JSON.parseObject(jsonObject.toString(), TpAmazonShopProduct.class);
				tpAmazonShopProductMapper.update(tpAmazonShopProduct);
				//保存当天查询到的产品报表排名信息
				if (tpAmazonShopProduct.getSalesRank() != null){
					TpAmazonShopProductReport amazonShopProductReport = new TpAmazonShopProductReport();
					amazonShopProductReport.setSalesRank(tpAmazonShopProduct.getSalesRank());
					amazonShopProductReport.setShopProductId(String.valueOf(tpAmazonShopProduct.getId()));
					amazonShopProductReport.setDataDate(nowDateStr);
					diySqlMapper.updateTpAmazonShopProductReport(amazonShopProductReport);
				}
			}
		}catch (Exception ex){
			apiResponse.setCode(500);
			apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getMessage());
		}
		return  apiResponse;
	}

	/**
	 * 定时获取亚马逊店铺销售产品信息
	 */
	@Override
	public ApiResponse getAmazonShopProductInventory(JSONObject jsonObject,List<TpAmazonShopProduct> amazonShopProductList, String nowDateStr,String encryptSecret) {
		ApiResponse apiResponse = new ApiResponse();
		try {
			AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
					.accessKeyId(MyConfig.getAmazonAwsAccessKey())
					.secretKey(MyConfig.getAmazonAwsAccessSecret())
					.region(jsonObject.get("awsRegion").toString())
					.build();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
					.roleArn(MyConfig.getAmazonRoleArn())
					.roleSessionName(MyConfig.getAmazonRoleSessionName())
					.build();
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey())
					.clientSecret(encryptSecret)
					.refreshToken(jsonObject.get("refreshToken").toString())
					.endpoint(MyConfig.getAmazonLwaEndpoint())
					.build();

			//根据get Inventory Summaries获取库存信息
			FbaInventoryApi fbaInventoryApi = new FbaInventoryApi.Builder()
					.awsAuthenticationCredentials(awsAuthenticationCredentials)
					.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
					.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
					.endpoint(jsonObject.get("amazonServiceUrl").toString())
					.build();
			String granularityType = "Marketplace";
			String granularityId = jsonObject.get("marketplaceId").toString();
			List<String> fbaInventoryMarketplaceIds = new ArrayList<String>();
			fbaInventoryMarketplaceIds.add(granularityId);
			List<String> fbaInventorySellerSkus = new ArrayList<>();
			for (TpAmazonShopProduct amazonShopProduct :amazonShopProductList){
				fbaInventorySellerSkus.add(amazonShopProduct.getSellerSku());
			}
			GetInventorySummariesResponse inventorySummariesResponse = null;
			boolean x = true;
			boolean isx = true;
			OffsetDateTime startTimeStr = null;
			while (x) {
				try {
					if (!isx){
						fbaInventorySellerSkus = null;
						Calendar calendar = new GregorianCalendar();
						Date startTime = calendar.getTime();
						startTime.setHours(0);
						startTime.setMinutes(0);
						startTime.setSeconds(0);
						startTimeStr = OffsetDateTime.parse(DateUtils.convertDateToTDate(startTime));
					}
					inventorySummariesResponse = fbaInventoryApi.getInventorySummaries(granularityType, granularityId, fbaInventoryMarketplaceIds, true, startTimeStr, fbaInventorySellerSkus, "");
				} catch (Exception ex) {
					if (ex.getMessage().equals("Text '' could not be parsed at index 0")) {
						isx = false;
						continue;
					}
					x = false;
					apiResponse.setCode(500);
					apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为：" + ex.getMessage());
					return apiResponse;
				}
				x = false;
			}
			if (inventorySummariesResponse != null) {
				if (inventorySummariesResponse.getPayload() != null && inventorySummariesResponse.getPayload().getInventorySummaries() != null && inventorySummariesResponse.getPayload().getInventorySummaries().size() > 0) {
					for (com.bo.sellingpartnerapi.Fbainventory.model.InventorySummary inventorySummary : inventorySummariesResponse.getPayload().getInventorySummaries()) {
						if (inventorySummary != null) {
							for (TpAmazonShopProduct tpAmazonShopProduct : amazonShopProductList) {
								if (tpAmazonShopProduct.getSellerSku().equals(inventorySummary.getSellerSku()) && tpAmazonShopProduct.getMarketplaceId().equals(jsonObject.get("marketplaceId").toString())) {
									tpAmazonShopProduct.setLastUpdatedTime(DateUtils.convertTDateToDate(inventorySummary.getLastUpdatedTime().toString()));
									if (inventorySummary.getInventoryDetails() != null) {
										com.bo.sellingpartnerapi.Fbainventory.model.InventoryDetails inventoryDetails = inventorySummary.getInventoryDetails();
										if (inventoryDetails != null) {
											tpAmazonShopProduct.setFulfillableQuantity(inventoryDetails.getFulfillableQuantity());
											tpAmazonShopProduct.setInboundWorkingQuantity(inventoryDetails.getInboundShippedQuantity());
											if (inventoryDetails.getUnfulfillableQuantity() != null) {
												tpAmazonShopProduct.setUnfulfillableQuantity(inventoryDetails.getUnfulfillableQuantity().getTotalUnfulfillableQuantity());
											}
											if (inventoryDetails.getResearchingQuantity() != null) {
												tpAmazonShopProduct.setReservedQuantity(inventoryDetails.getReservedQuantity().getTotalReservedQuantity());
											}
										}
									}
								}
							}
						}
					}
				}
			}
			//批量修改库存
			diySqlMapper.updateTpAmazonShopProductBatch(amazonShopProductList);
		}catch (Exception ex){
			apiResponse.setCode(500);
			apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getMessage());
		}
		return  apiResponse;
	}

	/**
	 * 定时获取亚马逊店铺销售产品信息（获取rank 销售排名）
	 */
	@Override
	public ApiResponse getRank(JSONObject jsonObject,List<TpAmazonShopProduct> tpAmazonShopProductList, String nowDateStr,String encryptSecret) {
		ApiResponse apiResponse = new ApiResponse();
		try {
			AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
					.accessKeyId(MyConfig.getAmazonAwsAccessKey())
					.secretKey(MyConfig.getAmazonAwsAccessSecret())
					.region(jsonObject.get("awsRegion").toString())
					.build();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
					.roleArn(MyConfig.getAmazonRoleArn())
					.roleSessionName(MyConfig.getAmazonRoleSessionName())
					.build();
			LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
					.clientId(MyConfig.getAmazonLwaClientKey())
					.clientSecret(encryptSecret)
					.refreshToken(jsonObject.get("refreshToken").toString())
					.endpoint(MyConfig.getAmazonLwaEndpoint())
					.build();
			CatalogApi catalogApi = new CatalogApi.Builder()
					.awsAuthenticationCredentials(awsAuthenticationCredentials)
					.lwaAuthorizationCredentials(lwaAuthorizationCredentials)
					.awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
					.endpoint(jsonObject.get("amazonServiceUrl").toString())
					.build();
			List<String> catalogMarketplaceIds = new ArrayList<String>();
			catalogMarketplaceIds.add(jsonObject.get("marketplaceId").toString());
			List<String> catalogIncludedData = new ArrayList<>();
			catalogIncludedData.add("attributes");
			catalogIncludedData.add("dimensions");
			catalogIncludedData.add("identifiers");
			catalogIncludedData.add("images");
			catalogIncludedData.add("productTypes");
			catalogIncludedData.add("salesRanks");
			catalogIncludedData.add("summaries");
			catalogIncludedData.add("relationships");

			List<String> identifiers = new ArrayList<>();
			for (TpAmazonShopProduct amazonShopProduct :tpAmazonShopProductList){
				identifiers.add(amazonShopProduct.getSellerSku());
			}
			ItemSearchResults searchCatalogItems;
			try {
				searchCatalogItems = catalogApi.searchCatalogItems(catalogMarketplaceIds, identifiers,
						"SKU",catalogIncludedData,null,jsonObject.get("sellerId").toString(), null,
						null,null,20,null,null);
			} catch (com.bo.sellingpartnerapi.Catalogitems20220401.invoker.ApiException ex) {
				apiResponse.setCode(500);
				apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getResponseBody());
				return apiResponse;
			}
			TpAmazonShopProductReport tpAmazonShopProductReport = null;
			List<TpAmazonShopProductReport> tpAmazonShopProductReportList = new ArrayList<>();
			if (searchCatalogItems != null){
				for (com.bo.sellingpartnerapi.Catalogitems20220401.model.Item items : searchCatalogItems.getItems()){
					for (TpAmazonShopProduct tpAmazonShopProduct : tpAmazonShopProductList) {
						if (tpAmazonShopProduct.getAsin().equals(items.getAsin()) && tpAmazonShopProduct.getMarketplaceId().equals(jsonObject.get("marketplaceId").toString())) {
							//获取产品品牌
							if (items.getSummaries() != null && items.getSummaries().size() > 0) {
								com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSummaryByMarketplace itemSummaryByMarketplace = items.getSummaries().get(0);
								if (itemSummaryByMarketplace != null) {
									tpAmazonShopProduct.setBrand(itemSummaryByMarketplace.getBrand());
								}
							}
							//获取产品图片
							if (items.getImages() != null && items.getImages().size() > 0) {
								com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImagesByMarketplace itemImagesByMarketplace = items.getImages().get(0);
								if (itemImagesByMarketplace != null && itemImagesByMarketplace.getImages() != null && itemImagesByMarketplace.getImages().size() > 0) {
									com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImage itemImage = itemImagesByMarketplace.getImages().get(0);
									if (itemImage != null) {
										tpAmazonShopProduct.setMainImage(itemImage.getLink());
									}
								}
							}
							//获取产品类别
							if (items.getProductTypes() != null && items.getProductTypes().size() > 0) {
								com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemProductTypeByMarketplace itemProductTypeByMarketplace = items.getProductTypes().get(0);
								if (itemProductTypeByMarketplace != null) {
									tpAmazonShopProduct.setProductType(itemProductTypeByMarketplace.getProductType());
								}
							}
							//获取产品排名
							if (items.getSalesRanks() != null && items.getSalesRanks().size() > 0) {
								com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSalesRanksByMarketplace itemSalesRanksByMarketplace = items.getSalesRanks().get(0);
								if (itemSalesRanksByMarketplace != null && itemSalesRanksByMarketplace.getDisplayGroupRanks() != null && itemSalesRanksByMarketplace.getDisplayGroupRanks().size() > 0) {
									com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDisplayGroupSalesRank itemDisplayGroupSalesRank = itemSalesRanksByMarketplace.getDisplayGroupRanks().get(0);
									if (itemDisplayGroupSalesRank != null) {
										tpAmazonShopProduct.setSalesRank(itemDisplayGroupSalesRank.getRank());
									}
								}
							}
							//获取产品尺寸与包装尺寸
							if (items.getDimensions() != null && items.getDimensions().size() > 0) {
								com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDimensionsByMarketplace itemDimensionsByMarketplace = items.getDimensions().get(0);
								if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getItem() != null) {
									tpAmazonShopProduct.setSizeLength((itemDimensionsByMarketplace.getItem().getLength() != null && itemDimensionsByMarketplace.getItem().getLength().getValue() != null) ? (itemDimensionsByMarketplace.getItem().getLength().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);//将英寸转成厘米
									tpAmazonShopProduct.setSizeHeight((itemDimensionsByMarketplace.getItem().getHeight() != null && itemDimensionsByMarketplace.getItem().getHeight().getValue() != null) ? (itemDimensionsByMarketplace.getItem().getHeight().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);
									tpAmazonShopProduct.setSizeWidth((itemDimensionsByMarketplace.getItem().getWidth() != null && itemDimensionsByMarketplace.getItem().getWidth().getValue() != null) ? (itemDimensionsByMarketplace.getItem().getWidth().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);
								}
								if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getPackage() != null) {
									tpAmazonShopProduct.setPackageLength((itemDimensionsByMarketplace.getPackage().getLength() != null && itemDimensionsByMarketplace.getPackage().getLength().getValue() != null) ? (itemDimensionsByMarketplace.getPackage().getLength().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);
									tpAmazonShopProduct.setPackageHeight((itemDimensionsByMarketplace.getPackage().getHeight() != null && itemDimensionsByMarketplace.getPackage().getHeight().getValue() != null) ? (itemDimensionsByMarketplace.getPackage().getHeight().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);
									tpAmazonShopProduct.setPackageWidth((itemDimensionsByMarketplace.getPackage().getWidth() != null && itemDimensionsByMarketplace.getPackage().getWidth().getValue() != null) ? (itemDimensionsByMarketplace.getPackage().getWidth().getValue().multiply(new BigDecimal("2.54")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);
									tpAmazonShopProduct.setPackageWeight((itemDimensionsByMarketplace.getPackage().getWeight() != null && itemDimensionsByMarketplace.getPackage().getWeight().getValue() != null) ? (itemDimensionsByMarketplace.getPackage().getWeight().getValue().multiply(new BigDecimal("0.45359237")).setScale(2, BigDecimal.ROUND_HALF_UP)) : BigDecimal.ZERO);//将磅转成千克
								}
							}
							if (tpAmazonShopProduct.getSalesRank() != null){
								tpAmazonShopProductReport = new TpAmazonShopProductReport();
								tpAmazonShopProductReport.setShopProductGuid(tpAmazonShopProduct.getGuid());
								tpAmazonShopProductReport.setShopProductId(String.valueOf(tpAmazonShopProduct.getId()));
								tpAmazonShopProductReport.setSalesRank(tpAmazonShopProduct.getSalesRank());
								tpAmazonShopProductReport.setDataDate(nowDateStr);
								tpAmazonShopProductReportList.add(tpAmazonShopProductReport);
							}
						}
					}
				}
				//批量修改商品信息
				diySqlMapper.updateTpAmazonShopProductBatchNew(tpAmazonShopProductList);
				//批量修改商品每天数据
				diySqlMapper.updateTpAmazonShopProductReportBatch(tpAmazonShopProductReportList);
			}
		}catch (Exception ex){
			apiResponse.setCode(500);
			apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getMessage());
		}
		return  apiResponse;
	}

}
